<template>
<!--  <div class="captcha-container">-->
<!--    <button -->
<!--      class="captcha-trigger"-->
<!--      @click="showCaptcha"-->
<!--      :disabled="loading"-->
<!--    >-->
<!--      {{ loading ? '验证中...' : '点击进行验证' }}-->
<!--    </button>-->
<!--  </div>-->
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'

const props = defineProps({
  // 从服务商获取的应用ID
  appId: {
    type: String,
    required: true
  },
  // 验证码语言设置，默认为简体中文
  language: {
    type: String,
    default: 'zh-cn'
  },
  // 验证码类型：popup(弹出式)或embed(嵌入式)
  type: {
    type: String,
    default: 'popup',
    validator: (value: string) => ['popup', 'embed'].includes(value)
  },
  // 是否启用暗黑模式
  darkMode: {
    type: [Boolean, String],
    default: false,
    validator: (value: any) => [true, false, 'force'].includes(value)
  },
  // 是否显示帮助按钮
  showHelp: {
    type: [Boolean, String],
    default: true
  }
})

const emit = defineEmits(['success', 'fail', 'ready', 'close'])

const loading = ref(false)
const captchaInstance = ref<any>(null)
const scriptLoaded = ref(false)

// 验证码回调函数
const captchaCallback = (result: any) => {
  loading.value = false
  
  if (result.ret === 0) {
    console.log(result.ticket)
    console.log(result.randstr)
    // 验证成功
    emit('success', {
      ticket: result.ticket,
      randStr: result.randstr,
    })
  } else {
    // 验证失败或取消
    emit('fail', {
      code: result.ret,
      message: getErrorMessage(result.ret)
    })
  }
}

// 获取错误信息
const getErrorMessage = (code: number): string => {
  const errorMap: Record<number, string> = {
    1: '用户取消验证',
    2: '验证超时',
    3: '验证码加载失败',
    4: '验证码配置错误',
    5: '验证码初始化失败'
  }
  return errorMap[code] || `未知错误 (${code})`
}

// 动态加载验证码JS 
const loadCaptchaScript = () => {
  return new Promise<void>((resolve, reject) => {
    if (scriptLoaded.value) {
      resolve()
      return
    }

    const script = document.createElement('script')
    script.src = 'https://captcha.api.hi.cn/captcha.js'
    script.async = true
    script.defer = true
    
    script.onload = () => {
      scriptLoaded.value = true
      resolve()
    }
    
    script.onerror = () => {
      reject(new Error('验证码脚本加载失败'))
    }

    document.head.appendChild(script)
  })
}

// 初始化验证码
const initCaptcha = async () => {
  try {
    loading.value = true
    
    if (!scriptLoaded.value) {
      await loadCaptchaScript()
    }

    const options = {
      type: props.type,
      userLanguage: props.language,
      enableDarkMode: props.darkMode,
      needFeedBack: props.showHelp,
      ready: (size: any) => {
        emit('ready', size)
        loading.value = false
      }
    }

    captchaInstance.value = new (window as any).FushuActionCaptcha(
      props.appId,
      captchaCallback,
      options
    )
  } catch (error) {
    loading.value = false
    emit('fail', {
      code: -1,
      message: '验证码初始化失败'
    })
    console.error('验证码初始化错误:', error)
  }
}

// 显示验证码
const showCaptcha = async () => {
  if (!captchaInstance.value) {
    await initCaptcha()
  }
  
  if (captchaInstance.value) {
    captchaInstance.value.show()
  }
}

// 关闭验证码
const closeCaptcha = () => {
  if (captchaInstance.value) {
    captchaInstance.value.close()
    emit('close')
  }
}

// 组件挂载时预加载JS
onMounted(() => {
  loadCaptchaScript().catch(error => {
    console.error('预加载验证码脚本失败:', error)
  })
})

// 组件卸载时清理
onBeforeUnmount(() => {
  if (captchaInstance.value) {
    captchaInstance.value.destroy?.() // 调用验证码的销毁方法
    captchaInstance.value = null      // 清空引用
  }
  scriptLoaded.value = false          // 重置加载状态
})


// 暴露方法给父组件
defineExpose({
  showCaptcha,
  closeCaptcha
})
</script>

<style scoped>
.captcha-container {
  display: inline-block;
}

.captcha-trigger {
  padding: 8px 15px;
  background-color: #ff5f16;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.captcha-trigger:hover {
  background-color: #e04b0d;
}

.captcha-trigger:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>